<template>
    <view class="page" :style="{'padding-top':(navigationbarHeight+5)+'px'}" :class="postType=='vote'?'vote-wrapper':''">
        <TopBar :showName="showName" :postName.sync="postName"></TopBar>
        <view v-if="postType!='vote'" >
			<view class="post-title">
			    <input type="text" v-model="postTitle" class="post-title-input" placeholder="取个有趣的标题吧" @focus.stop="entryFocus" @blur.stop="entryBlur" v-if="titleYN"/>
			</view>
			<view class="post-content">
			    <textarea id="content" fixed v-model="postContent" :show-confirm-bar="false" auto-height placeholder="来吧，发挥你的文采~~" @focus.stop="entryFocus" @blur.stop="entryBlur"></textarea>
			</view>
			<view class="post-picture">
			    <view class="add-picture-img" v-for="(item, index) in images" :key="index">
			        <img :src="item" @click="showPic(item)" v-if="postType=='image'" mode="aspectFill"/>
			        <video :src="item" @click="showPic(item)" v-if="postType=='video'"/>
			        <view class="del-picture-btn" @click.stop="delImagesList(index)">
			            <img src="/static/img/redXX.png" />
			        </view>
			    </view>
			    <view class="add-picture-btn"  @click="chooseImage" v-if="imagesShow">
			        <img src="/static/img/add-img.png">
			    </view>
			</view>
		</view>
		
		<!-- 投票贴 -->
		<view v-if="postType=='vote'" >
			<view class="post-title">
				<textarea  fixed v-model="postContent" :show-confirm-bar="false" auto-height placeholder="投票标题" @focus.stop="entryFocus" @blur.stop="entryBlur"></textarea>
			</view>
			<view class="divide"></view>
			<view class="vote-options">
				<div class="vote-options-item" v-for="(vote,key) of voteItem" :key="key">
					<view class="delete-btn" @click="deleteVoteItem(key)">
						<img src="/static/img/redXX.png"  />
					</view>
					<view class="vote-options-main vote-line">
						<input type="text" placeholder="选项内容" v-model="vote.content">
						<view class="vote-picture-btn"  v-if="vote.img_url==''"  @click="chooseVoteImage(key)">
						    <img src="/static/img/add-img.png" >
						</view>
						<img class="vote-picture" mode="aspectFill" :src="vote.img_url" v-if="vote.img_url!=''"  @click="chooseVoteImage(key)">
					</view>
				</div>
				<div class="vote-options-item" >
					<view class="delete-btn" @click="addVoteItem">
						<img src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/bbMachine/add-blue.png"  />
					</view>
					
					<view class="vote-options-main vote-add" @click="addVoteItem">
						<view>添加选项</view>
					</view>
				</div>
			</view>
			<view class="divide"></view>
			<!-- 截止时间 -->
			<view class="vote-deadline vote-line">
				<view class="tit">截止时间</view>
				<view class="vote-day">
					<view @click="voteDeadline(-1)" :style="{'backgroundColor':voteDeadlineType==-1?'#FFE226':''}">不截止</view>
					<view @click="voteDeadline(3)" :style="{'backgroundColor':voteDeadlineType==3?'#FFE226':''}">3天</view>
					<view @click="voteDeadline(7)" :style="{'backgroundColor':voteDeadlineType==7?'#FFE226':''}">7天</view>
					<view @click="voteDeadline(0)" :style="{'backgroundColor':voteDeadlineType==0?'#FFE226':''}">自定义</view>
				</view>
			</view>
			<view class="vote-choose-day" v-if="voteDeadlineType==0">
				<view class="tit">截止时间</view>
				<view>{{voteDeadlineTime|filterTime}}</view>
				<picker mode="date"  :start="minDate"  @change="getDate">
				    <view class="picker-btn" >
				    	<view>请选择</view>
				    	<img src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/bbMachine/arrow-gray.png" alt="">
				    </view>
				  </picker>
				
			</view>
			<!-- 截止时间end -->
		</view>
		<!-- 投票贴 -->
		
		
<!--        <view class="post-sort-show" v-if="postSort!=''">-->
<!--            已选择分类：<text @click="this.$refs.postbottoms.chooseSort()">{{postSort}}</text>-->
<!--        </view>-->
        <view class="post-submit-btn">
<!--            <button type="warn" @click="sendPostArticle">发布</button>-->
        </view>
        <Postbottom ref="postbottoms" :postType.sync="postType" :fatherValue.sync="postList" :NotName.sync="no_name" :postName.sync="postName" :postSort.sync="postSort" :altUserList.sync="altUserList"></Postbottom>
		<datePicker @getDate="getDate" ref="datePicker"/>
    </view>
</template>

<script>
    import TopBar from "@/pages/components/topBar/topBar";
    import Postbottom from "@/pages/components/post-bottom-nav/postbottom";
	import datePicker from '@/pages/components/datePicker'
    export default {
        name: "graphicposts",
        components: {Postbottom, TopBar,datePicker},
        data(){
			let date=new Date()
			let minDate=`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
            return{
				altUserList:[],//alt总的数据
				altUserIdArr:[],//@别人的id数组
                navigationbarHeight: getApp().globalData.navStyle.navigationbarHeight,
                showName: 'post',
                postName:{},
                postTitle:'',
                postContent:'',
				richText:'',//上传的富文本
                postType: 'text',
                img_ids:[],
                video_id: [],
                postEntry:'',
                images: [],
                imagesShow: true,
                postSort:{},
                no_name: 0, //0-所有人可见，1-匿名
                titleYN: false,
                postList: {
                    bottomnavHeight: '0px',
                    //表情定义
                    hideEmoji:false
                },
				
				// 投票
				minDate,
				voteHeader:'<img style="width:40rpx;height:40rpx;display: inline-block;vertical-align: top;" src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/bbMachine/invitation-vote.png" alt=""><span style="color:#128FFF; margin-right:10px">投票</span>',
				voteItem:[],//投票项
				voteDeadlineType:-1,//截止时间类型
				voteDeadlineTime:'',//截止时间》日期格式
				showPopoupFlag:false,
            }
        },
		filters:{
			filterTime(val){
				return val.split(' ')[0]
			}
		},
		watch:{
			images(newValue){
			    if (newValue.length>0){
                    switch (this.postType) {
                        case 'image':
                            if (newValue.length >= 9){
                                this.imagesShow = false
                            }
                            break;
                        case 'video':
                            if (newValue.length >= 1){
                                this.imagesShow = false
                            }
                            break;
                    }
                } else {
			        this.postType = 'text';
                    this.imagesShow = true;
                }

			},
            altUserList(newValue){
                let num = this.postContent.match(/@(.*?)\s/gi);
                // console.log(num)
                if (num != null){
                    if (num.length < newValue.length){
                        let str = newValue[newValue.length-1];
                        const content=`@${str.basicUserInfo.nickname} `;
                        this.postContent+=content;
                    }
                }else {
                    if (newValue.length>0){
                        let str = newValue[0];
                        const content=`@${str.basicUserInfo.nickname} `;
                        this.postContent+=content;
                    }
                }

			},
            postContent(newValue){
                this.postContent = newValue;
			    let num = newValue.match(/@(.*?)\s/gi);
			    // console.log(num)
			    if (num == null){
			        if (this.altUserList.length>0){
                        this.postContent = this.postContent.substring(0,this.postContent.lastIndexOf("@"));
			            this.altUserList = [];
                    }
                } else {
			        if (num.length != this.altUserList.length){
			            // console.log("ass")
                        this.postContent = this.postContent.substring(0,this.postContent.lastIndexOf("@"));
                        let altNameArr=num.map(item=>{
                            return item.trim().split('@')[1]
                        })
                        console.log(altNameArr)
                        this.altUserList.forEach((item,index)=>{
                            if(altNameArr.includes(item.basicUserInfo.nickname)){
                                return
                            }else {
                                this.altUserList.splice(index,1);
                            }
                        })
                    }


                }
            }
		},
        onLoad(query){
            console.log(query)
            if (query.circleName){
                this.postName ={
                    name : query.circleName,
                    id : query.circle_id
                } ;
            }

        },
        onShow(){
            var pages = getCurrentPages();
            var currPage = pages[pages.length - 1];
            // console.log(json)
            if (currPage.data.postNames) {
                this.postName = currPage.data.postNames;
            }
            if (currPage.data.postSorts) {
                this.postSort = currPage.data.postSorts;
            }
            if (currPage.data.altUserLists) {
                this.altUserList = currPage.data.altUserLists;
            }
        },
        methods:{
			addVoteHeader(){
				//投票帖
				if(this.postType=='vote'){
					if(this.richText.indexOf(this.voteHeader)==-1){
						this.richText=`${this.voteHeader}${this.richText}`
					}
				}else {
					//非投票帖
					this.richText.replace(this.voteHeader,'')
				}
			},
			replaceContent(text){
				let richText=text;
                this.richText = text;
				let userIdArr=[]
				// 找出[表情的匹配]
				let patternE=/\[([^(\]|\[)]*)\]/g;
				richText=text.replace(patternE,(item,index)=>{
					return this.replaceEmoji(item)
				})
				this.richText=richText
				//找出@的匹配
				let pattern=/@(.*?)\s/gi;
				let arr=richText.match(pattern);
				
				if(!arr){return}
				
				let altNameArr=arr.map(item=>{
					return item.trim().split('@')[1]
				})
				this.altUserList.forEach((item,index)=>{
					if(altNameArr.includes(item.basicUserInfo.nickname)){
						let dom=`<a style="color:#00CCFF;font-size:28rpx;line-height:40rpx;" href="/pages/person/customHomepage/customHomepage?userId=${item.follow_user_id}">@${item.basicUserInfo.nickname}</a>`
						richText=richText.replace(pattern,dom);
						userIdArr.push(item.follow_user_id)
					}
				})

                this.richText = richText;
				this.altUserIdArr=userIdArr;
				// console.log(this.richText);
			},
			//替换表情符号为图片
			replaceEmoji(str){
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g,(item, index)=>{
					// console.log("item: " + item);
					for(let i=0;i<this.$refs.postbottoms.emojiList.length;i++){
						let row = this.$refs.postbottoms.emojiList[i];
						for(let j=0;j<row.length;j++){
							let EM = row[j];
							if(EM.alt==item){
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径 
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								let onlinePath = 'https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/bbMachine/emoji/'
								let imgstr = '<img src="'+onlinePath+EM.url+'" alt="'+EM.alt+'" style="width:40rpx;height:40rpx;display: inline-block;vertical-align: top;">';
								// console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				return replacedStr;
			},
            editorChange(e){
                this.postContent = e.detail.html
            },

            //点击发布上传图片或视频
            async onSendPostArticle(){
                // console.log(this.postContent)
				if(this.postType=='vote'){
					//投票帖
					this.sendVote();
					return
				}
                if (this.images.length>0){
                    if (this.postType == "image"&&this.img_ids.length == this.images.length){
                        this.sendPostArticle();
                    }else if (this.postType == "video"&&this.video_id.length == this.images.length) {
                        this.sendPostArticle();
                    }else {
                        uni.showToast({
                            icon:'none',
                            title:"文件上传中，请稍后"
                        })
                    }
                }else{
					this.sendPostArticle();
				}

            },
            //上传图片
            uploadImg(url){
			    var _this = this;
			    for (let i = 0 ; i< url.length; i++){
                    wx.uploadFile({
                        url: _this.$api.BASE_URL+'file/upload-img',
                        filePath: url[i],
                        name: 'photo',
                        header: {
                            'content-type': 'application/json' // 默认值
                        },
                        success: function (res) {
                            res.data = JSON.parse(res.data);
                            if (res.data.level == 'success') {
                                _this.img_ids.push(res.data.data.id)
                            }else {
                                uni.showToast({
                                    icon:'none',
                                    title:res.data.message
                                })
                            }
                        }
                    })
                }

            },
			async sendVote(){
				//发布投票贴
				if(this.voteItem.length<1){
					uni.showToast({
						icon:'none',
						title:'至少添加2个选项'
					})
					return
				}
				await this.replaceContent(this.postContent);
				this.addVoteHeader();
				let voteItem=this.voteItem.map(item=>{
					return {img_id:item.img_id,content:item.content}
				})
				
				let voteItemNoEmpty=voteItem.every(item=>{
					return item.content!=''
				})
				if(!voteItemNoEmpty){
					uni.showToast({
						icon:'none',
						title:'选项内容不能为空'
					})
					return
				}
				let params = {
				    title : this.postTitle,
				    content: this.richText,
				    user_token: uni.getStorageSync('userToken'),
				    circle_id: this.postName.id,
				    classify_id: this.postSort.id,
					at_user_ids:this.altUserIdArr,
				    no_name: this.no_name,
					vote_detail:voteItem,
					vote_deadline:this.voteDeadlineTime
				}
				const res = await this.$api.sendPostArticle(params);
				if (res.data.level == 'success'){
				    let _this = this;
				    uni.showToast({
				        icon:'none',
				        title:res.data.message,
				        duration:2000
				    })
				    setTimeout(function () {
				        uni.redirectTo({
				            url:'/pages/circlebar/circlebarhome/circlebarhome?circle_id='+_this.postName.id
				        })
				    },2000)
				
				}else {
				    uni.showToast({
				        icon:'none',
				        title:res.data.message
				    })
				}
			},
            //发帖功能
            async sendPostArticle(){
				await this.replaceContent(this.postContent);
				this.addVoteHeader()
                let params = {
                    title : this.postTitle,
                    content: this.richText,
                    user_token: uni.getStorageSync('userToken'),
                    circle_id: this.postName.id,
                    img_ids:this.img_ids,
                    classify_id: this.postSort.id,
                    video_id: this.video_id,
					at_user_ids:this.altUserIdArr,
                    no_name: this.no_name
                }
                const res = await this.$api.sendPostArticle(params);
                if (res.data.level == 'success'){
                    let _this = this;
                    uni.showToast({
                        icon:'none',
                        title:res.data.message,
                        duration:2000
                    })
                    setTimeout(function () {
                        uni.redirectTo({
                            url:'/pages/circlebar/circlebarhome/circlebarhome?circle_id='+_this.postName.id
                        })
                    },2000)

                }else {
                    uni.showToast({
                        icon:'none',
                        title:res.data.message
                    })
                }
            },
            //输入框对焦
            entryFocus(e){
                this.postList.bottomnavHeight = e.detail.height+'px';
                this.postEntry = e.target.id;
                this.postList.hideEmoji = false;
            },
            entryBlur(){
                this.postList.hideEmoji = false;
                this.postList.bottomnavHeight = '0px';
            },
			vote(){
				//进行投票
				this.postType='vote'
			},
			addVoteItem(){
				this.voteItem.push({
					img_id:'',
					img_url:'',
					content:''
				})
			},
			deleteVoteItem(index){
				this.voteItem.splice(index,1)
			},
			async chooseVoteImage(index){
				//上传投票项图片
				let res=await this.$currency.upLoadImage();
				let data=JSON.parse(res.data);
				console.log(data)
				if(data.level=='success'){
					let item=this.voteItem[index];
					item.img_url=data.data.img_url;
					item.img_id=data.data.id;
					this.voteItem.splice(index,1,item)
				}else{
					uni.showToast(data.message)
				}
				console.log(this.voteItem)
			},
			voteDeadline(type){
				//选择投票截止时间
				this.voteDeadlineType=type;
				console.log(this.voteDeadlineType)
				this.voteDeadlineTime=''
				if(type!=-1 && type!==0){
					this.voteDeadlineTime= this.getDateStr(type);
				}
				if(type==-1){
					this.voteDeadlineTime=''
				}
			},
			showDatePicker(){
				//显示日期选择
				this.showPopoupFlag=true;
				this.$refs.datePicker.toggleVisible()
			},
			getDate(e){
				//获取年月日
				let [year,month,day]=e.detail.value.split('-')
				this.voteDeadlineTime=this.getDateStr({year,month,day})
			},
			
			getDateStr(AddDayCount) { 
				
				var dd = new Date();
				if(AddDayCount instanceof Object){
					dd.setDate(+AddDayCount.day)
					dd.setMonth(+AddDayCount.month-1)
					dd.setFullYear(+AddDayCount.year)
				}else{
					dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
				}
				
				
				var y = dd.getFullYear(); 
				var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期，不足10补0
				var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号，不足10补0
				var h = dd.getHours();  
				h=h < 10 ? ('0' + h) : h;  
				var minute = dd.getMinutes();  
				minute = minute < 10 ? ('0' + minute) : minute;  
				var second=dd.getSeconds();  
				second=second < 10 ? ('0' + second) : second;  
				return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 
			},
            //选择图片
            chooseImage(){
				if(this.postType=='vote'){
					this.images=[];
					this.img_ids=[]
					this.postType = 'text';
					return
				}
				this.postType = 'image';
			    var ImageCount = 9-this.images.length;
			    if (ImageCount>0){
                    uni.chooseImage({
                        sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
                        sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
                        count: ImageCount,
                        success: res => {
                            
                            this.images= this.images.concat(res.tempFilePaths)
                            // 限制最多只能留下3张照片
                            this.uploadImg(res.tempFilePaths);
                            // $digest(this)
                        },
						fail:err=>{
							if(this.images.length==0){//避免取消选择图片后，不能切换到选择video
								this.postType='text'
							}
						}
                    })
                } else {
                    uni.showToast({
                        icon:'none',
                        title:"已达到最大可选图数量~"
                    })
                }

            },
            // 预览图片
            showPic(url){
                uni.previewImage({
                    indicator:"none",
                    current:url,
                    urls: this.images
                });
            },
            //取消已选择图片
            delImagesList(id){
                this.images.splice(id,1);
                if (this.postType == 'image'){
                    this.img_ids.splice(id,1);
                } else {
                    this.video_id.splice(id,1);
                }

            },
            //选择视频
            chooseVideo(){
				if(this.postType=='vote'){
					this.postType = 'text';
					this.images=[];
					this.video_id=[]
					return
				}
				this.postType = 'video';
                uni.chooseVideo({
                    sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
                    camera: 'back',
                    maxDuration:60,
                    success: res => {
                        console.log(res)
                        this.images.push(res.tempFilePath);
                        this.uploadVideo(this.images)
                    },
					fail:err=>{
						if(this.images.length==0){//避免取消选择视频后，不能切换到选择image
							this.postType='text'
						}
						
					}
                })
            },
            //上传视频
            uploadVideo(url){
                var _this = this;
                for (let i = 0 ; i< url.length; i++){
                    wx.uploadFile({
                        url: _this.$api.BASE_URL+'file/upload-video',
                        method: 'POST',
                        filePath: url[i],
                        name: 'video',
                        header: {
                            'content-type': 'multipart/form-data' // 默认值
                        },
                        success: function (res) {
                            res.data = JSON.parse(res.data);
                            if (res.data.level == 'success') {
                                console.log(res)
                                _this.video_id.push(res.data.data.id)
                            }else {
                                uni.showToast({
                                    icon:'none',
                                    title:res.data.message
                                })
                            }
                        },
                    })
                }

            },
        },
    }
</script>

<style scoped lang="scss">
	@import '~@/static/scss/mixin.scss';
	//投票样式
	.vote-wrapper{
			margin:0 !important;
			padding-bottom: 240rpx;
			.divide{
				background: #F3F5F6;
				width: 100%;
				height: 20rpx;
			}
			.vote-line{
				border-bottom: 2rpx solid #F3F5F6;
			}
			.post-title{
			    padding:0 30rpx;
				textarea{
					width: 100%;
					line-height: 40rpx;
					font-size: 32rpx;
					color: #000000;
					min-height: 200rpx;

				}
			    .post-title-input{
			        width: 100%;
			        height: 50rpx;
			        line-height: 50rpx;
			        font-size: 40rpx;
			        color: #7e7e7e;
			    }
			}
			.vote-options{
				
				.vote-options-item{
					padding:20rpx 30rpx;
					@include flex(flex-start);
					.delete-btn{
						width:44rpx;
						height: 44rpx;
					}
					 
					 .vote-options-main{
						 @include flex(space-between);
						 flex:1;
						 padding:20rpx 0 20rpx  20rpx;
						 input{
						 	flex:1;
							font-size:32rpx;
						 }
						 .vote-picture-btn{
						     display: inline-block;
						     width: 120rpx;
						     height: 120rpx;
						     border: 2rpx dashed #CCCCCC;
						     border-radius: 20rpx;
						     img{
						         width: 30%;
						         height: 30%;
						         margin: 35%;
						     }
						 }
						 .vote-picture{
						     display: inline-block;
						     width: 120rpx;
						     height: 120rpx;
						     border-radius: 20rpx;
						 }
						 .vote-add{
							 color:#3279FF;
							 font-size:32rpx;
						 }
					 }
					
				}
			}
			
			//截止时间
			.vote-deadline{
				margin:20rpx 30rpx;
				.tit{
					font-size: 32rpx;
					font-weight: 600;
				}
				.vote-day{
					@include flex(space-between);
					padding:40rpx 0;
					view{
						background-color: #F3F5F6;
						padding:10rpx 25rpx;
						border-radius:24rpx;
						margin:0 20rpx;
					}
				}
			}
			.vote-choose-day{
				margin:20rpx 30rpx;
				@include flex(space-between);
				.tit{
					font-size: 32rpx;
					font-weight: 600;
				}
				.picker-btn{
					@include flex();
					color:#BBBCBF;
					img{
						width: 40rpx;
						height: 40rpx;
					}
				}
			}
				
				
	}
    .page{
		margin: 30rpx;

        .post-title{
            padding-bottom: 20rpx;
            /*border-bottom: 2rpx solid #c7c7c7;*/
            .post-title-input{
                width: 100%;
                height: 50rpx;
                line-height: 50rpx;
                font-size: 40rpx;
                color: #7e7e7e;
            }
        }
        .post-content{
            padding: 30rpx 10rpx;
            /*min-height: 200rpx;*/
            textarea{
                width: 100%;
                line-height: 40rpx;
                font-size: 32rpx;
                color: #000000;
                min-height: 200rpx;
            }
        }
        .post-picture{
            padding: 0.2vw;
            margin-top: 30rpx;
            .add-picture-btn{
                display: inline-block;
                width: 28vw;
                height: 28vw;
                margin: 1vw;
                border: 2rpx dashed #CCCCCC;
                border-radius: 20rpx;
                img{
                    width: 30%;
                    height: 30%;
                    margin: 35%;
                }
            }
            .add-picture-btn.hide{
                display: none;
            }
            .add-picture-img{
                position: relative;
                display: inline-block;
                width: 28.5vw;
                height: 28.5vw;
                margin: 1vw;
                overflow: visible;
                img{
                    border-radius: 20rpx;
                    overflow: hidden;
                }
                .del-picture-btn{
                    width: 40rpx;
                    height: 40rpx;
                    position: absolute;
                    background: #ffffff;
                    border-radius: 360rpx;
                    top: -1vw;
                    right: -1vw;
                }
            }
        }
        .post-sort-show{
            margin: 20rpx 0;
            padding: 20rpx;
            font-size: 24rpx;
            line-height: 40rpx;
            text{
                font-size: 24rpx;
                background: #d1d1d1;
                line-height: 30rpx;
                padding: 5rpx 10rpx;
            }
        }
        .post-submit-btn{
            margin: 50rpx 0;
        }
    }
</style>